<?php

namespace Xin\VarDumper\Hyperf;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler as HyperfExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Xin\VarDumper\VarDumperException;

class ExceptionHandler extends HyperfExceptionHandler
{
    public function __construct(protected StdoutLoggerInterface $logger)
    {
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 阻止异常冒泡
        $this->stopPropagation();

        return $response->withBody(new SwooleStream($throwable->render()));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof VarDumperException;
    }
}
